package com.ecric.http.http;

import android.Manifest;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.ecric.http.R;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.io.File;

@EActivity(R.layout.activity_muti_thread_download)
public class MutiThreadDownloadActivity extends AppCompatActivity {

    @ViewById(R.id.txt_muti_download)
    TextView txt;
    private String path = "http://img3.iqilu.com/data/attachment/forum/201308/21/192654ai88zf6zaa60zddo.jpg";
    private String saveFilePath ;
    private FileDownUtil fileDownUtil;

    @AfterViews
    void initData(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){//如果api 23 需要判断用户是否已授权
            if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) == -1 &&
                    ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == -1  ){
                startDownload();//用户已授权 开始下载
            }else {//未授权 申请所需权限
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE},0x123);
            }
        }else {//用户已授权 开始下载
            startDownload();
        }
    }

    /**
     * 更新Ui
     */
    @UiThread
    void updateUi(String update){
        txt.setText(update);
    }

    /**
     * 开启后台线程，在后台线程进行下载
     */
    @Background
    void download(){
        fileDownUtil.download();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x123){
            if (grantResults[0] == 0 && grantResults[1] == 0){
                Log.e("已授权: ","存储空间读取权限！");
                startDownload();
            }
        }
    }

    /**
     * 开始下载
     */
    private void startDownload() {
        saveFilePath = new File(getCachePath(),"temp.jpg").getAbsolutePath();
        fileDownUtil = FileDownUtil.getInstance(path,saveFilePath,3);
        //设置下载进度监听
        fileDownUtil.setOnDownloadProgressListener(new FileDownUtil.DownloadProgressListener() {
            @Override
            public void onDownloadSize(int downloadSize, int fileSize) {
                updateUi("文件总大小："+ fileSize + "\n" + "已下载：" + downloadSize);
            }
        });
        download();
    }

    /**
     * 获取缓存路径
     * @return
     */
    private String getCachePath(){
        String appPath = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            appPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "com.ecric.http";
        }else {
            appPath = Environment.getDataDirectory().getAbsolutePath() + File.separator + "com.ecric.http";
        }
        File file = new File(appPath);
        if (!file.exists()){
           file.mkdirs();
        }
        Log.e("文件路径====》",appPath);
        return appPath;
    }

}
